<?php

namespace App\Http\Controllers;

use App\Models\BindingRecord;
use App\Models\ChatRecords;
use App\Models\FriendList;
use App\Models\User;
use GatewayClient\Gateway;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;

/**
 * 客户端聊天控制器
 * Class ChatController
 * @package App\Http\Controllers
 */
class ChatController extends BaseController
{
    //前端(用户端)加载试图
    public function index(Request $request)
    {
        $user_id = $request->input('user_id', null);//客户端用户id
        $token = $request->input('invitation_code_key', null);//客户端用户token
        $addressee_id = $request->input('addressee_id',null);//好友的id

//        if (!$user_id || !$token || !$addressee_id) {
//            $this->send(400, '缺少参数');
//        }

        //去客户的项目中users表求职者验证token是否正确
        $verify_token = User::where('id',$user_id)->value('invitation_code_key');
        if ($verify_token != $token) {
            $this->send(403, '身份验证失败');
        }

        return view('web.chat.index', compact('user_id','addressee_id'));
    }

    //绑定用户id与workmain_id
    public function binding(Request $request)
    {
        $user_id = $request->input('user_id');//数据库中用户真实id
        $addressee_id = $request->input('addressee_id', 0);//收件人id
        $role = $request->input('role','2');//当前登录用户身份|1:客服,2:用户
        $client_id = $request->input('client_id');//workmain的临时id标识

        $addressee_name = User::where('id',$addressee_id)->value('nickname');
        //绑定信息存在则更新/入库
        $res = [
            'msg' => '绑定成功',
            'type' => 'binding_success',
            'bind_id' => 0,
            'addressee_id' => $addressee_id,
            'addressee_name' => $addressee_name,
        ];

        //换取全局通用bind_id
        $binding = BindingRecord::where([
            ['user_id', $user_id],
            ['role', $role],//1:客服,2:用户
        ])->first();
        if ($binding) {
            //更新绑定信息
            $binding->update(['client_id' => $client_id]);
            $res['bind_id'] = $binding['id'];
        } else {
            //创建绑定关系
            $date = date('Y-m-d H:i:s');
            $bind_id = BindingRecord::insertGetId([
                'created_at' => $date,
                'user_id' => $user_id,
                'role' => $role,
                'client_id' => $client_id,
            ]);
            $res['bind_id'] = $bind_id;//绑定后的id,此id为我们IM只平台中用户与用户件通信标识身份的唯一id
        }

        //开始绑定
        Gateway::bindUid($client_id, $res['bind_id']);

//        Cache::put('customer_service_id_' . $res['bind_id'], $addressee_id, now()->addMinutes(20));


        return $this->send(200, 'success', $res);
    }

    //分配客服
    private function assignCustomerService()
    {
        //获取全部在线的客服
        $bind_id = BindingRecord::where('role', 1)->pluck('id');
        if (!count($bind_id)) {
            $this->send(500, '暂无在线客服');
        }
        $ol_bind_id = [];
        Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
        foreach ($bind_id as $v) {
            $res = Gateway::isUidOnline($v);//检查uid是否在线
            if ($res) {
                $ol_bind_id[] = $v;
            }
        }
        //随机选中一个客服id与当前用户成为好友关系
        if ($ol_bind_id){
            $service_id = $ol_bind_id[array_rand($ol_bind_id)];
        }else{
            //没有客服在线
            $service_id = 1;//默认客服id
        }
        //返回选中的客服id

        return $service_id;
    }

    /**
     * 创建好友关系
     * @param int $waiter_bind_id 客服bind_id
     * @param int $client_bind_id 用户bing_in
     */
    private function createFriendships(int $waiter_bind_id, int $client_bind_id)
    {
        $friend = FriendList::where([
            ['waiter_bind_id', $waiter_bind_id],
            ['client_bind_id', $client_bind_id],
        ])->first();
        if (!$friend) {
            FriendList::create([
                'waiter_bind_id' => $waiter_bind_id,
                'client_bind_id' => $client_bind_id,
            ]);
        }
    }

    /**
     * 发送消息
     * @param Request $request
     */
    public function sendMassage(Request $request)
    {
        $message = [
            'bind_id' => $request->input('bind_id'),//当前用户id
            'role' => $request->input('role','2'),//用户身份,1:客服,2:用户
            'addressee_id' => $request->input('addressee_id'),//收件人id
            'type' => $request->input('type'),//消息类型
            'content' => $request->input('content'),//消息内容
        ];
        if (!$message['bind_id'] || !$message['addressee_id'] || !$message['type'] || !$message['content']) {
            return $this->send(500, '发送失败');
        }

        if (!in_array($message['type'], ['text', 'images', 'link'])) {
            return $this->send(403, '消息类型不合法');
        }

        $addressee_id = BindingRecord::where('user_id', $message['addressee_id'])->value('id');

        $is_read = 2;//是否已读|默认为1:否,2:是
        if ($message['role'] == 2) {
            //通过缓存得到当前的好友是否正在和当前客户聊天
            $service_user_id = Cache::get('customer_service_id_' . $message['addressee_id']);
            //如果可和正在和当前客户聊天就把消息状态变为已读
            if ($service_user_id == $message['bind_id']) {
                $is_read = 1;
            }
        }
        $content = json_encode($message,JSON_UNESCAPED_UNICODE);
        //将消息存入数据库
        ChatRecords::create([
            'sender_id' => $message['bind_id'],//发件人id|(数据来自binding_records表)
            'addressee_id' => $message['addressee_id'],//收件人id|(数据来自binding_records表)
            'content' => $message,//发送的内容json格式
            'message_type' => $message['type'],//消息类型|text:文本(字符串),images:图片(json格式),link:链接(json格式)
            'is_read' => $is_read,//是否已读|默认为1:否,2:是
        ]);

        Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
        Gateway::sendToUid($addressee_id, $content);//给发件人的uid网站页面发送数据
        $this->send(200, 'success');
    }


}
